/**
 * @author   thienchau
 * @time     5:52:17 PM Feb 19, 2013
 * @filename DateHelper.java
 */

package com.cdn.allmobilestore.ulti;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.util.Log;

public class DateHelper {

	public static final int MIN_YEARS_OLD = 18;
	public static final String format1 = "MM/dd/yyyy";
	public static final String format2 = "yyyy-MM-dd";

	public static String convertDateString(String dateInput,
			String formatInput, String formatOutput) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateInput);
		sdf.setLenient(false);
		Date date = null;
		try {
			date = sdf.parse(dateInput);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		sdf.applyPattern(formatOutput);
		return sdf.format(date);
	}

	public static boolean isThisDateValid(String dateToValidate,
			String dateFromat) {
		if (dateToValidate == null) {
			return false;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
		sdf.setLenient(false);
		try {
			// if not valid, it will throw ParseException
			Date date = sdf.parse(dateToValidate);
			System.out.println(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean isEnoughYearOld(String birthday, String dateFromat,
			int yearOld) {
		Calendar curCalendar = Calendar.getInstance();
		Calendar birCalendar = Calendar.getInstance();
		if (birthday == null) {
			return false;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
		sdf.setLenient(false);
		Date date;
		try {
			// if not valid, it will throw ParseException
			date = sdf.parse(birthday);
			System.out.println(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
		birCalendar.setTime(date);

		Log.i("date",
				"curCalendar " + curCalendar.get(Calendar.YEAR) + " "
						+ curCalendar.get(Calendar.MONTH) + " "
						+ curCalendar.get(Calendar.DAY_OF_MONTH));
		Log.i("date",
				"birCalendar " + birCalendar.get(Calendar.YEAR) + " "
						+ birCalendar.get(Calendar.MONTH) + " "
						+ birCalendar.get(Calendar.DAY_OF_MONTH));

		if (curCalendar.get(Calendar.YEAR) - birCalendar.get(Calendar.YEAR) > yearOld) {
			return true;
		} else if (curCalendar.get(Calendar.YEAR)
				- birCalendar.get(Calendar.YEAR) < yearOld) {
			return false;
		} else {
			if (birCalendar.get(Calendar.MONTH) < curCalendar
					.get(Calendar.MONTH)) {
				return true;
			} else if (birCalendar.get(Calendar.MONTH) > curCalendar
					.get(Calendar.MONTH)) {
				return false;
			} else {
				if (birCalendar.get(Calendar.DAY_OF_MONTH) <= curCalendar
						.get(Calendar.DAY_OF_MONTH)) {
					return true;
				} else if (birCalendar.get(Calendar.DAY_OF_MONTH) > curCalendar
						.get(Calendar.DAY_OF_MONTH)) {
					return false;
				}
			}
		}
		return true;
	}
}
